package java7;

import java.io.IOException;
import java.net.URL;
import java.nio.file.*;
import java.util.List;

/**
 * @author lwx
 * @create 2018-06-22 15:51
 */
public class WatchServiceTest {


    public static void main(String[] args) throws IOException {

        TryWithResourcesTest tt = new TryWithResourcesTest();
        String root = tt.getRoot();
        //final String path = root + "a.txt";
        final String path = "F://文档";
        System.out.println(path);
        final WatchService watchService = FileSystems.getDefault().newWatchService();
        Path p = Paths.get(path);
        p.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_CREATE);


        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {

                        WatchKey watchKey = watchService.take();
                        List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
                        for (WatchEvent<?> event : watchEvents) {
                            //TODO 根据事件类型采取不同的操作。。。。。。。
                            System.out.println("[" + path + "/" + event.context() + "]文件发生了[" + event.kind() + "]事件");
                        }
                        watchKey.reset();
                    }
                } catch (Exception e2) {


                }
            }
        }) {


        };


        thread.setDaemon(false);
        thread.start();
        // 增加jvm关闭的钩子来关闭监听
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    watchService.close();
                } catch (Exception e) {
                }
            }
        }
        ));


    }


    ;


    public String getRoot() {
        URL url = TryWithResourcesTest.class.getResource("");
        System.out.println(url.getPath());
        return this.getClass().getResource("/").getPath();

    }
}
